package gorouting

import (
	"sync"
)

type MyPool struct {
	maxWorkers int
	workChain  chan func()
	stopChain  chan bool
	wg         sync.WaitGroup
}

func ConstructPool(maxWorkers int, chainSize int) *MyPool {
	return &MyPool{
		maxWorkers: maxWorkers,
		workChain:  make(chan func(), chainSize),
		stopChain:  make(chan bool),
		wg:         sync.WaitGroup{},
	}
}

func (mp *MyPool) PoolStart() {
	for i := 0; i < mp.maxWorkers; i++ {
		mp.wg.Add(1)
		go mp.Workers()
	}
}

func (mp *MyPool) Workers() {
	defer mp.wg.Done()
	for {
		select {
		case task := <-mp.workChain:
			task()
		case <-mp.stopChain:
			return
		}
	}
}

func (mp *MyPool) Submit(job func()) {
	select {
	case <-mp.stopChain:
		println("现在pool已经关闭")
	default:
		mp.workChain <- job
	}
}

func (mp *MyPool) Shutdown() {
	close(mp.stopChain)
	mp.wg.Wait()
	close(mp.workChain)
}

//
//func main() {
//	pool := NewPool(3, 10) // 3个协程，10个任务队列
//	pool.Start()
//
//	// 提交15个任务
//	for i := 0; i < 15; i++ {
//		//id := i
//		pool.Submit(func() {
//			time.Sleep(500 * time.Millisecond)
//			//fmt.Printf("Task %d done by %d\n", id, <-getGoroutineID())
//		})
//	}
//
//	time.Sleep(3 * time.Second)
//	pool.Shutdown()
//	fmt.Println("Pool gracefully stopped")
//}
